﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using BugTacker.Common;
using BugTracker.BusinessEntities.Entities.Issue;
using BugTracker.BusinessLogic.BTUser;
using BugTracker.BusinessLogic.Issue;
using BugTracker.BusinessLogic.Project;
using BugTracker.Core.Infrastructure.Exceptions;
using BugTracker.WebUX.Admin.Modules.AppCode;
using BugTracker.WebUX.WebCode;
using Microsoft.Practices.Unity;
using BugTracker.BusinessLogic.ReportedBy;
using System.Data.SqlTypes;

namespace BugTracker.WebUX.Workspace.Modules
{
    public partial class UCIssueDetail : BTUserControlBase
    {
       #region page load

        protected void Page_Load(object sender, EventArgs e)
        {
            ActionInfoBox.Text = "Ready";
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
            InitButtonPanel();
            if (!Page.IsPostBack)
            {
                BindDropDown();
                ValidateUrlParam();
            }
        }

        #endregion

        #region bind dropdown

        private void BindDropDown()
        {

            this.CategoryDropDown.DataSource = Global.IoC.Container.Resolve<ICategoryService>().Load(); ;
            this.CategoryDropDown.DataBind();

            this.IssueTypeDropDown.DataSource = Global.IoC.Container.Resolve<IIssueTypeService>().Load();;
            this.IssueTypeDropDown.DataBind();

            this.IssuePriorityTypeDropDown.DataSource = Global.IoC.Container.Resolve<IIssuePriorityTypeService>().Load();
            this.IssuePriorityTypeDropDown.DataBind();

            this.IssueStatusDropDown.DataSource = Global.IoC.Container.Resolve<IIssueStatusTypeService>().Load();
            this.IssueStatusDropDown.DataBind();

            IList<User> assignees = new List<User>();
            var users = Global.IoC.Container.Resolve<IBTUserService>().Load();
            foreach (var user in users)
            {
                assignees.Add(new User(user.BTUserID, user.FirstName + " " + user.LastName));
            }

            this.IssueAssigneeDropDown.DataSource = assignees;
            this.IssueAssigneeDropDown.DataBind();

            this.ProjectDropDown.DataSource = Global.IoC.Container.Resolve<IProjectService>().Load();
            this.ProjectDropDown.DataBind();

            this.IssueSeverityTypeDropDown.DataSource = Global.IoC.Container.Resolve<IIssueSeverityTypeService>().Load();
            this.IssueSeverityTypeDropDown.DataBind();

            this.IssueResolutionTypeDropDown.DataSource = Global.IoC.Container.Resolve<IIssueResolutionTypeService>().Load();
            this.IssueResolutionTypeDropDown.DataBind();

            this.ReproducedDropDown.DataSource = Global.IoC.Container.Resolve<IReproducedService>().Load();
            this.ReproducedDropDown.DataBind();

            IList<Reportee> reportee = new List<Reportee>();
            var reported = Global.IoC.Container.Resolve<IReportedByService>().Load();
            foreach (var item in reported)
            {
                reportee.Add(new Reportee(item.ReportedByID, item.FirstName + " " + item.LastName));
            }

            this.ReportedByDropDown.DataSource = reportee;
            this.ReportedByDropDown.DataBind();
        }

        #endregion

        #region check url param

        private void ValidateUrlParam()
        {
            string param = Request.QueryString[BTHttpApplication.UrlParam.ISSUE_ID];
            if (!string.IsNullOrEmpty(param))
            {
                int id = 0;
                Int32.TryParse(param, out id);
                if (id != 0)
                {
                    this.Key = id;
                    BindData(id);
                }
            }
            else
            {
                SetInfoBoxAdding();
            }
        }

        #endregion

        #region bind data

        private void BindData(int id)
        {
            try
            {
                var model = Global.IoC.Container.Resolve<IIssueService>().LoadById(id);
                if (model != null)
                {
                    this.Entity = model;
                    CommonRoutines.DropDownSelectByValue(this.CategoryDropDown, model.CategoryID);
                    this.NameTextBox.Text = CommonRoutines.Decode(model.Name);
                    this.DescriptionTextBox.Text = CommonRoutines.Decode(model.Description);
                    CommonRoutines.DropDownSelectByValue(this.IssueTypeDropDown, model.IssueTypeID);
                    CommonRoutines.DropDownSelectByValue(this.IssuePriorityTypeDropDown, model.IssuePriorityTypeID);
                    CommonRoutines.DropDownSelectByValue(this.IssueStatusDropDown, model.IssueStatusTypeID);
                    CommonRoutines.DropDownSelectByValue(this.IssueAssigneeDropDown, model.IssueAssigneeID);
                    CommonRoutines.DropDownSelectByValue(this.ProjectDropDown, model.ProjectID);
                    CommonRoutines.DropDownSelectByValue(this.IssueSeverityTypeDropDown, model.IssueSeverityTypeID);
                    CommonRoutines.DropDownSelectByValue(this.IssueResolutionTypeDropDown, model.IssueResolutionTypeID);
                    CommonRoutines.DropDownSelectByValue(this.ReproducedDropDown, model.ReproducedID);
                    //ReportedOnTextBox.Text = DateTime.Now.ToString(BTHttpApplication.Constants.DATETIME_FORMAT);
                    ReportedOnTextBox.Text = CommonRoutines.EnsureDateTime(model.ReportedOn).ToString(BTHttpApplication.Constants.DATETIME_FORMAT);
                    CommonRoutines.DropDownSelectByValue(this.ReportedByDropDown, model.ReportedByID);
                    if(model.ResolvedOn.HasValue)
                    {
                        if (model.ResolvedOn != DateTime.MinValue)
                        {
                            ResolvedOnTextBox.Text = CommonRoutines.EnsureDateTime(model.ResolvedOn).ToString(BTHttpApplication.Constants.DATETIME_FORMAT);
                        }
                    }

                    this.CommentTextBox.Text = CommonRoutines.Decode(model.Comments);
                    this.IsActiveCheckBox.Checked = model.IsActive;
                    this.SetInfoBoxUpdating();
                }
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region button panel

        private void InitButtonPanel()
        {
            ButtonPanel.PrepareResources();
            ButtonPanel.Submit.Visible = true;
            ButtonPanel.Return.Visible = true;
            ButtonPanel.Submit.Click += SubmitButton_Click;
            ButtonPanel.Return.Click += ReturnButton_Click; 
        }

        #endregion

        #region infobox

        private void SetInfoBoxAdding()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.AddingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.blue;
            ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Save;
        }

        private void SetInfoBoxUpdating()
        {
            MessageInfoBox.Visible = true;
            MessageInfoBox.Text = Resources.Phrases.EditingRecord;
            MessageInfoBox.MessageType = InfoBox.InfoBox.MsgType.blue;
            ButtonPanel.Submit.Text = Resources.Controls.ButtonText_Update;
        }

        private void SetInfoBoxError(string message)
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = message;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.red;
        }

        #endregion

        #region saveadding

        private void SaveAdding()
        {
            var model = new Issue();
            var guid = Guid.NewGuid();
            model.ProjectID = 0;
            model.CategoryID = Convert.ToInt32(this.CategoryDropDown.SelectedValue);
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            model.Description = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.DescriptionTextBox.Text, 255));
            model.IssueTypeID = Convert.ToInt32(this.IssueTypeDropDown.SelectedValue);
            model.IssuePriorityTypeID = Convert.ToInt32(this.IssuePriorityTypeDropDown.SelectedValue);
            model.IssueStatusTypeID = Convert.ToInt32(this.IssueStatusDropDown.SelectedValue);
            model.IssueAssigneeID = Convert.ToInt32(this.IssueAssigneeDropDown.SelectedValue);
            model.ProjectID = Convert.ToInt32(this.ProjectDropDown.SelectedValue);
            model.IssueSeverityTypeID = Convert.ToInt32(this.IssueSeverityTypeDropDown.SelectedValue);
            model.IssueResolutionTypeID = Convert.ToInt32(this.IssueResolutionTypeDropDown.SelectedValue);
            model.ReproducedID = Convert.ToInt32(this.ReproducedDropDown.SelectedValue);
            model.ReportedOn = CommonRoutines.EnsureDateTime(ReportedOnTextBox.Text);
            model.ReportedByID = Convert.ToInt32(this.ReportedByDropDown.SelectedValue);
            model.ResolvedOn = CommonRoutines.EnsureDateTime(ResolvedOnTextBox.Text);
            model.Comments  = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.CommentTextBox.Text, 255));
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.RowGuid = guid;
            model.CreatedOn = DateTime.UtcNow;
            model.ModifiedOn = DateTime.UtcNow;
            model.UserId = Guid.Parse(BTSecurity.GetUserId());
            try
            {
                Global.IoC.Container.Resolve<IIssueService>().InsertObject(model);
                this.Entity = Global.IoC.Container.Resolve<IIssueService>().LoadByGuid(guid);

                ActionInfoBox.Text = Resources.Phrases.InsertSuccessful;
                SetInfoBoxUpdating();

            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save editing

        private void SaveEditing()
        {
            var model = (Issue)this.Entity;
            model.CategoryID = Convert.ToInt32(this.CategoryDropDown.SelectedValue);
            model.Name = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.NameTextBox.Text, 50));
            model.Description = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.DescriptionTextBox.Text, 255));
            model.IssueTypeID = Convert.ToInt32(this.IssueTypeDropDown.SelectedValue);
            model.IssuePriorityTypeID = Convert.ToInt32(this.IssuePriorityTypeDropDown.SelectedValue);
            model.IssueStatusTypeID = Convert.ToInt32(this.IssueStatusDropDown.SelectedValue);
            model.IssueAssigneeID = Convert.ToInt32(this.IssueAssigneeDropDown.SelectedValue);
            model.ProjectID = Convert.ToInt32(this.ProjectDropDown.SelectedValue);
            model.IssueSeverityTypeID = Convert.ToInt32(this.IssueSeverityTypeDropDown.SelectedValue);
            model.IssueResolutionTypeID = Convert.ToInt32(this.IssueResolutionTypeDropDown.SelectedValue);
            model.ReproducedID = Convert.ToInt32(this.ReproducedDropDown.SelectedValue);
            model.ReportedOn = CommonRoutines.EnsureDateTime(ReportedOnTextBox.Text);
            model.ReportedByID = Convert.ToInt32(this.ReportedByDropDown.SelectedValue);
            model.ResolvedOn = CommonRoutines.EnsureDateTime(ResolvedOnTextBox.Text);
            model.Comments  = CommonRoutines.Encode(CommonRoutines.EnsureMaxLength(this.CommentTextBox.Text, 255));
            model.IsActive = this.IsActiveCheckBox.Checked;
            model.IsDeleted = false;
            model.ModifiedOn = DateTime.UtcNow;
            model.UserId = Guid.Parse(BTSecurity.GetUserId());

            try
            {
                Global.IoC.Container.Resolve<IIssueService>().UpdateObject(model);
                this.Entity = Global.IoC.Container.Resolve<IIssueService>().LoadByGuid(model.RowGuid);

                ActionInfoBox.Text = Resources.Phrases.UpdateSuccessful;
                SetInfoBoxUpdating();
            }
            catch (BugTrackerExpection e)
            {
                SetInfoBoxError(e.Message);
            }
        }

        #endregion

        #region save

        private void Save()
        {
            if (Page.IsValid)
            {
                if (this.Entity == null)
                {
                    SaveAdding();
                }
                else
                {
                    SaveEditing();
                }
            }
        }

        #endregion

        #region button events

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        protected void ReturnButton_Click(object sender, EventArgs e)
        {
            Response.Redirect(BTHttpApplication.AppPaths.IssueList);
        }

        #endregion
    }
}